<template>
  <div class="publish-container">
    <el-card class="publish-card" shadow="never">
      <div slot="header" class="card-header">
        <h3>发布{{ ctype === 'needs' ? '求购' : '供应' }}信息</h3>
      </div>

      <el-form 
        ref="form" 
        :model="form" 
        label-width="100px" 
        label-position="left"
        class="publish-form">
        
        <!-- 图片上传 -->
        <el-form-item :label="ctype === 'needs' ? '添加图片(可选)' : '添加图片'" required>
          <el-upload
            class="image-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :limit="3"
            list-type="picture-card"
            :file-list="fileList"
            :on-change="handleChange"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :on-error="handleError"
            :class="{ 'upload-disabled': isUploadDisabled }">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="upload-tip">
              {{ ctype === 'needs' ? '最多上传3张图片(可选)' : '最多上传3张图片' }}
            </div>
          </el-upload>
        </el-form-item>

        <!-- 标题 -->
        <el-form-item label="标题" prop="title" required>
          <el-input 
            v-model="form.title" 
            placeholder="请输入标题"
            clearable
            class="form-input">
          </el-input>
        </el-form-item>

        <!-- 内容 -->
        <el-form-item label="详细内容" prop="content" required>
          <el-input
            type="textarea"
            :rows="5"
            v-model="form.content"
            placeholder="请输入详细内容"
            resize="none"
            class="form-textarea">
          </el-input>
        </el-form-item>

        <!-- 价格 -->
        <el-form-item 
          label="价格" 
          prop="price"
          v-if="ctype !== 'needs'"
          required>
          <el-input-number
            v-model="form.price"
            :min="0"
            :precision="2"
            controls-position="right"
            class="price-input">
          </el-input-number>
          <span class="price-unit">元</span>
        </el-form-item>

        <!-- 发布按钮 -->
        <el-form-item class="form-footer">
          <el-button 
            type="primary" 
            @click="publishClick"
            :disabled="isDisabled"
            :loading="submitting"
            class="publish-btn">
            发布信息
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { addOrder } from "../api/order";

export default {
  name: "PublishMessage",
  props: {
    ctype: {
      type: String,
      required: true,
      validator: value => ['goods', 'needs'].includes(value)
    }
  },
  data() {
    return {
      form: {
        title: "",
        content: "",
        price: 0,
        picture: ""
      },
      fileList: [],
      isUploadDisabled: false,
      submitting: false,
      uploadUrl: this.$store.state.fileUploadRoad + "/file/upload/order",
      uploadHeaders: {
        Authorization: window.localStorage.token
      }
    };
  },
  computed: {
    isDisabled() {
      const { title, content, price } = this.form;
      if (this.ctype === 'needs') {
        return !title || !content;
      } else {
        return !title || !content || price <= 0 || !this.form.picture;
      }
    }
  },
  methods: {
    handleError(err) {
      this.$message.error("图片上传失败");
      console.error(err);
    },
    handleSuccess(response) {
      if (response.flag) {
        this.form.picture = response.data;
        this.$message.success(response.message);
      } else {
        this.$message.error(response.data);
      }
    },
    handleChange(file, fileList) {
      this.isUploadDisabled = fileList.length >= 3;
    },
    handleRemove(file, fileList) {
      this.isUploadDisabled = fileList.length >= 3;
      if (fileList.length === 0) {
        this.form.picture = "";
      }
    },
    async publishClick() {
      if (this.ctype !== 'needs' && !this.form.picture) {
        this.$message.warning("请上传商品图片");
        return;
      }

      this.submitting = true;
      try {
        const res = await addOrder({
          title: this.form.title,
          content: this.form.content,
          price: this.form.price,
          type: this.ctype,
          picture: this.form.picture
        });

        if (res.flag) {
          this.$message.success(res.message);
          this.$router.push(`/home/user/published${this.ctype}`);
        } else {
          this.$message.error(res.data);
        }
      } catch (err) {
        console.error("发布失败:", err);
        this.$message.error("发布失败");
      } finally {
        this.submitting = false;
      }
    }
  }
};
</script>

<style lang="less" scoped>
.publish-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;

  .publish-card {
    border-radius: 8px;

    .card-header {
      border-bottom: 1px solid #ebeef5;
      padding: 15px 20px;

      h3 {
        margin: 0;
        font-size: 18px;
        color: #303133;
      }
    }

    .publish-form {
      padding: 20px 30px;

      .image-uploader {
        /deep/ .el-upload {
          width: 150px;
          height: 150px;
          line-height: 150px;
        }

        .upload-tip {
          margin-top: 8px;
          font-size: 12px;
          color: #909399;
        }
      }

      .upload-disabled {
        /deep/ .el-upload {
          display: none;
        }
      }

      .form-input {
        width: 100%;
      }

      .form-textarea {
        width: 100%;
      }

      .price-input {
        width: 200px;
        margin-right: 10px;
      }

      .price-unit {
        color: #606266;
      }

      .form-footer {
        margin-top: 30px;
        text-align: center;

        .publish-btn {
          width: 200px;
        }
      }
    }
  }
}
</style>